import { IMessage } from "@/types/chat";
import { ISession } from "@/types/session";
import dayjs from "dayjs";

function formatRelativeTime(timestamp: string) {
  if (timestamp == "") timestamp = new Date().toString();
  const now = dayjs();
  const date = dayjs(timestamp);
  const diffInSeconds = now.diff(date, "second");
  if (diffInSeconds < 60) {
    return "现在";
  } else if (diffInSeconds < 3600) {
    const minutes = Math.floor(diffInSeconds / 60);
    return `${minutes}分钟前`;
  } else if (diffInSeconds < 86400) {
    const hours = Math.floor(diffInSeconds / 3600);
    return `${hours}小时前`;
  } else {
    const days = Math.floor(diffInSeconds / 86400);
    return `${days}天前`;
  }
}

// dayjs格式化为 xxxx-xx-xx xx:xx
function FormatTime(timestamp: string) {
  return dayjs(timestamp).format("YYYY-MM-DD HH:mm");
}

// 根据时间排序
function SortByLatest(arr: ISession[], _data: IMessage): ISession[] {
  return arr.sort((a, b) => dayjs(b.updatedAt).valueOf() - dayjs(a.updatedAt).valueOf());
}
// 显示聊天消息间隔 （兼容 "YYYY-MM-DD HH:mm:ss"）
function GetTimeLabel(arr: any, index: number, item: IMessage): string | null {
  const currentTime = new Date(item.updatedAt);
  if (index === 0) {
    return currentTime.toLocaleString();
  }
  const prevMessage = arr[index - 1];
  const prevTime = new Date(prevMessage.createdAt);
  const TEN_MINUTES = 10 * 60 * 1000;
  if (currentTime.getTime() - prevTime.getTime() > TEN_MINUTES) {
    if (currentTime.toDateString() !== prevTime.toDateString()) {
      const month = (currentTime.getMonth() + 1).toString().padStart(2, "0");
      const day = currentTime.getDate().toString().padStart(2, "0");
      const time = currentTime.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      });
      return `${month}/${day} ${time}`;
    } else {
      return currentTime.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      });
    }
  }
  return null;
}

function RecordTimer(seconds: number): string {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;
  return [hours > 0 ? hours : null, minutes.toString().padStart(2, "0"), remainingSeconds.toString().padStart(2, "0")]
    .filter(Boolean)
    .join(":");
}

function FormatBirthDate(date: string): string {
  return dayjs(date).format("YYYY-MM-DD");
}
// 判断时间是否相差三分钟之内
function IsWithin3Minutes(time1: string, time2 = new Date()) {
  const date1 = dayjs(time1);
  const date2 = dayjs(time2);

  // 检查时间有效性
  if (!date1.isValid() || !date2.isValid()) {
    console.error("Invalid date:", { time1, time2 });
    return false;
  }
  const diffSeconds = Math.abs(date1.diff(date2, "second"));
  console.log(date1, date2, diffSeconds);

  return diffSeconds <= 180;
}
export { formatRelativeTime, FormatTime, SortByLatest, GetTimeLabel, RecordTimer, FormatBirthDate, IsWithin3Minutes };
